<template>
  <div>
    <div v-if="showTitle" class="el-subheader">{{ title }}</div>
    <div class="upload-button-container">
      <template v-if="!isView">
        <el-button
          type="warning"
          :loading="loading"
          @click="triggerFileInput"
        >
          上传附件
        </el-button>

        <input
          type="file"
          ref="fileInput"
          :multiple="multiple"
          :accept="accept"
          @change="onFileChange"
          style="display: none"
        />
      </template>
      <div class="uploaded-files">
        <div
          v-for="file in files"
          :key="file.AttachmentId"
          class="uploaded-file"
        >
          <span class="file-name">{{ file.DisplayName }}</span>
          <div class="file-actions">
            
            <el-button
              v-if="!isView"
              type="text"
              size="mini"
              @click="removeFile(file)"
            >
              <i class="el-icon-delete"></i>
              删除
            </el-button>
            <a v-else :href="download(file)" target="_blank" download>
              <el-button type="text" size="mini">
                <i class="el-icon-download"></i>
                下载
              </el-button>
            </a>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialog" width="600px">
      <div slot="title" class="d-flex align-center justify-space-between">
        <span class="headline">文件预览</span>
        <span style="flex:1"></span>
        <el-button type="text" icon="el-icon-close" @click="dialog = false"></el-button>
      </div>
      <div>
        <img v-if="currentFile && currentFile.FileAllPath" :src="currentFile.FileAllPath" class="responsive-image" />
        <div v-else class="text-center pa-4">
          <i class="el-icon-document"></i>
          <p>无法预览此文件</p>
        </div>
      </div>
    </el-dialog>

    <!-- <p class="upload-hint">只允许上传 {{ accept }} 文件，且不超过 5MB</p> -->
  </div>
</template>

<script>
import { uploadFile } from "@/api/api";

export default {
  name: 'UploadFile',
  props: {
    isView: { type: Boolean, default: false },
    title: { type: String, default: '上传文件' },
    showTitle: { type: Boolean, default: true },
    files: { type: Array, default: () => [] },
    maxFiles: { type: Number, default: 50 },
    // 将默认值从 '*' 改为 只允许 Word 和 PDF
    accept: { type: String, default: '.doc,.docx,.pdf' },
    multiple: { type: Boolean, default: true }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      currentFile: null
    }
  },
  methods: {
    onFileChange(event) {
      const newFiles = Array.from(event.target.files || [])
      if (this.files.length + newFiles.length > this.maxFiles) {
        alert(`最多只能上传 ${this.maxFiles} 个文件`)
        return
      }
      this.uploadFiles(newFiles)
    },
    removeFile(file) {
      const idx = this.files.indexOf(file)
      if (idx > -1) this.files.splice(idx, 1)
    },
    triggerFileInput() {
      this.$refs.fileInput && this.$refs.fileInput.click()
    },
    async uploadFiles(newFiles) {
      this.loading = true
      try {
        const allowed = ['doc', 'docx', 'pdf']
        for (const f of newFiles) {
          const ext = (f.name || '').split('.').pop().toLowerCase()
          if (!allowed.includes(ext)) {
            alert('仅支持上传 Word 或 PDF 文件（.doc .docx .pdf）')
            continue
          }
          const formData = new FormData()
          formData.append('file', f)
          const fileatt = await uploadFile(formData)
          // 兼容不同后端返回结构
          const data = fileatt && (fileatt.data || fileatt.Data || fileatt)
          if (data) {
            // 标准化结构
            const normalized = {
              AttachmentId: data.AttachmentId || data.id || Date.now(),
              DisplayName: data.DisplayName || data.name || f.name,
              FilePath: data.FilePath || data.path || '',
              FileAllPath: data.FileAllPath || data.url || ''
            }
            this.files.push(normalized)
          }
        }
      } catch (err) {
        console.error('上传失败:', err)
        alert('上传失败，请稍后重试')
      } finally {
        this.loading = false
        if (this.$refs.fileInput) this.$refs.fileInput.value = ''
      }
    },
    viewFile(item) {
      this.currentFile = item || null
      this.dialog = !!this.currentFile
    },
    download(item) {
      const data = item || {}
      const path = data.FilePath || ''
      const name = data.DisplayName || ''
      // 保持与后端接口一致
      return `/api/file/Download?path=${encodeURIComponent(path)}&name=${encodeURIComponent(name)}`
    }
  }
}
</script>

<style scoped>
.upload-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
  margin-bottom: 10px;
}

.upload-button-container {
  margin-bottom: 10px;
}

.uploaded-files {
  display: flex;
  flex-direction: column; /* 垂直排列文件列表 */
  margin-top: 10px;
}

.uploaded-file {
  display: flex;
  justify-content: space-between; /* 左右对齐 */
  align-items: center;
  margin-bottom: 10px;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.uploaded-file:hover {
  background-color: rgba(0, 0, 0, 0.1); /* 鼠标悬停时的背景色 */
}

.file-name {
  flex-grow: 1; /* 文件名占据剩余空间 */
  margin-right: 10px; /* 文件名与操作图标之间的间距 */
}

.file-actions {
  display: flex;
  align-items: center;
}

.view-icon,
.delete-icon {
  cursor: pointer;
  margin-left: 5px; /* 图标之间的间距 */
}

.upload-hint {
  margin-top: 10px;
  color: #888;
}

.responsive-image {
  width: 100%; /* 宽度铺满 */
  height: auto; /* 高度自适应 */
}

.v-dialog {
  max-width: 600px; /* 设置弹窗最大宽度 */
  margin: auto; /* 居中弹窗 */
}

.el-subheader { /* 简单替代 v-subheader */
  font-size: 14px;
  color: #909399;
  padding: 8px 0;
}
</style>
